#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
检查Java文件中的注释编码问题
"""
import os
import re
import chardet
from pathlib import Path

def is_garbled_chinese(text):
    """检查文本中是否有乱码的中文字符"""
    if not text:
        return False
    
    # 检查是否有常见的乱码模式
    garbled_patterns = [
        r'[\x80-\xff]{2,}',  # 连续的非ASCII字符，可能是乱码
        r'æ|è|ø|Ã|©|®|¼|½|¾',  # 常见的乱码字符
    ]
    
    for pattern in garbled_patterns:
        if re.search(pattern, text):
            return True
    
    return False

def check_file_encoding(file_path):
    """检查文件编码和注释乱码情况"""
    try:
        with open(file_path, 'rb') as f:
            raw_data = f.read()
            
        # 检测编码
        detected = chardet.detect(raw_data)
        encoding = detected['encoding']
        confidence = detected['confidence']
        
        # 尝试解码
        try:
            content = raw_data.decode(encoding or 'utf-8')
        except:
            content = raw_data.decode('utf-8', errors='replace')
            encoding = 'utf-8 (with errors)'
            confidence = 0.0
        
        # 提取注释
        comments = []
        
        # 单行注释
        single_line_comments = re.findall(r'//.*$', content, re.MULTILINE)
        comments.extend(single_line_comments)
        
        # 多行注释
        multi_line_comments = re.findall(r'/\*.*?\*/', content, re.DOTALL | re.MULTILINE)
        comments.extend(multi_line_comments)
        
        # Javadoc注释
        javadoc_comments = re.findall(r'/\*\*.*?\*/', content, re.DOTALL | re.MULTILINE)
        comments.extend(javadoc_comments)
        
        # 检查注释中的乱码
        garbled_comments = []
        for comment in comments:
            if is_garbled_chinese(comment):
                garbled_comments.append(comment)
        
        return {
            'encoding': encoding,
            'confidence': confidence,
            'total_comments': len(comments),
            'garbled_comments': len(garbled_comments),
            'has_garbled': len(garbled_comments) > 0
        }
        
    except Exception as e:
        return {
            'encoding': 'unknown',
            'confidence': 0.0,
            'error': str(e),
            'total_comments': 0,
            'garbled_comments': 0,
            'has_garbled': False
        }

def find_java_files(directory):
    """查找所有Java文件"""
    java_files = []
    for root, _, files in os.walk(directory):
        for file in files:
            if file.endswith('.java'):
                java_files.append(os.path.join(root, file))
    return java_files

def main():
    """主函数"""
    java_last_war_dir = Path(__file__).parent.parent.parent
    java_files = find_java_files(java_last_war_dir)
    
    print(f"找到 {len(java_files)} 个Java文件")
    
    total_files = 0
    files_with_garbled_comments = 0
    
    for file_path in java_files:
        result = check_file_encoding(file_path)
        total_files += 1
        
        if result.get('has_garbled', False):
            files_with_garbled_comments += 1
            relative_path = os.path.relpath(file_path, java_last_war_dir)
            print(f"发现注释乱码: {relative_path}")
            print(f"  编码: {result['encoding']} (置信度: {result['confidence']:.2f})")
            print(f"  总注释数: {result['total_comments']}, 乱码注释数: {result['garbled_comments']}")
            print()
    
    print(f"\n统计:")
    print(f"总Java文件数: {total_files}")
    print(f"有注释乱码的文件数: {files_with_garbled_comments}")
    print(f"比例: {files_with_garbled_comments/total_files*100:.1f}%")

if __name__ == "__main__":
    main()